var Host = "http://14.23.146.234:7000/emsc-pub-api";  //测试

//var Host = "http://192.168.11.21:7003/emsc-pub-api";   //本地 盛

//var Host = "http://emsc.cx580.com:8093/emsc-pub-api";  //体验

// var Host = "https://emsc.cx580.com/emsc-pub-api";   //生产

var Rule = {
    required: {key: "required", value: "不能为空!"}
};

//develop（开发版），trial（体验版），release（正式版）
var FootConvenientService = {
    appid: 'wxc1257fe34b8d3264',
    path: '',
    envVersion: 'release'
};

/** 返回是将pageObj的data赋值
 * address（选择后的文本地址xxx-xx-xx）
 * @param pageObj
 * @returns {Promise}
 * 先取默认地址
 */

function initAddress(pageObj, callBack) {
    pageObj.setData({
        isShow: false, // 显示区域选择框
        showDistrict: true // 默认为省市区三级区域选择
    });
    var opt1 = {
        url: Host + "/wx/c/p.ajax",
        data: {
            type: 'directCar'
        },
        showLoadFlag: "false",
        sucFn: function (province) {
            var firstProvince = province.body.result[25];
            var provinceName = [];
            for (var i = 0; i < province.body.result.length; i++) {
               // if (province.body.result[i].id == 440000) {   //目前限制只能选择广东
                provinceName.push(province.body.result[i])
              /*      break;
                }*/
            }
            pageObj.setData({ //默认选择获取的省份第一个省份数据
                proviceData: provinceName
            });

            var opt2 = {
                url: Host + "/wx/c/c1.ajax",
                data: {"provinceId": provinceName[0].id},//firstProvince.id  provinceName[0].id
                showLoadFlag: "false",
                sucFn: function (city) {
                    var firstCity = city.body.result[0];
                    pageObj.setData({
                        cityData: city.body.result
                    });
                    var opt3 = {
                        url: Host + "/wx/c/c2.ajax",
                        data: {"cityId": firstCity.id},
                        showLoadFlag: "false",
                        sucFn: function (district) {
                            pageObj.setData({
                                value: [0, 0, 0],//默认广东省
                                districtData: district.body.result
                            });

                            callBack && callBack()
                        }
                    };
                    ajax(opt3);
                }
            };
            ajax(opt2);
        }
    };
    ajax(opt1)
}

function bindAddressChange(e, pageObj) {
    const current_value = e.detail.value, _data = pageObj.data;
    if (current_value.length > 2) {
        if (pageObj.data.value[0] !== current_value[0]) {  // 滑动省份
            var opt1 = {
                url: Host + "/wx/c/c1.ajax",
                showLoadFlag: "false",
                data: {"provinceId": _data.proviceData[current_value[0]].id},
                sucFn: function (city) {
                    pageObj.setData({
                        value: [current_value[0], 0, 0],
                        cityData: city.body.result
                    });
                    var opt2 = {
                        url: Host + "/wx/c/c2.ajax",
                        showLoadFlag: "false",
                        data: {"cityId": city.body.result[0].id},
                        sucFn: function (district) {
                            if (district.body.result.length > 0) {
                                pageObj.setData({
                                    districtData: district.body.result
                                });
                            }
                        }
                    };
                    ajax(opt2);
                }
            };
            ajax(opt1);
        } else if (pageObj.data.value[0] === current_value[0] && pageObj.data.value[1] !== current_value[1] && pageObj.data.value[2] === current_value[2]) { // 滑动城市
            var opt = {
                url: Host + "/wx/c/c2.ajax",
                data: {"cityId": _data.cityData[current_value[1]].id},
                showLoadFlag: "false",
                sucFn: function (district) {
                    if (district.body.result.length > 0) {
                        pageObj.setData({
                            districtData: district.body.result,
                            value: [current_value[0], current_value[1], 0]
                        });
                    }
                }
            };
            ajax(opt);
        } else if (pageObj.data.value[0] === current_value[0] && pageObj.data.value[1] === current_value[1] && pageObj.data.value[2] !== current_value[2]) { // 滑动地区
            pageObj.setData({value: current_value});
        }
    }
}

//台湾签注初始化地址
function initTwHouse(pageObj) {
    pageObj.setData({
        isShow: false, // 显示区域选择框
        showDistrict: true // 默认为省市区三级区域选择
    });

    var opt1 = {
        url: Host + '/wx/etw/ad.ajax',
        data: {
            bizType: pageObj.data.visaType,
            bizProvinceId: pageObj.data.bizProvinceId
        },
        showLoadFlag: "false",
        sucFn: function (result) {
            var province = result.body;
            pageObj.setData({//默认选择获取的省份第一个省份数据
                twHouseProviceData: [{
                    id: province.cityList[0].provinceId,
                    name: province.cityList[0].provinceName
                }]
            });
            pageObj.setData({
                twHouseCityData: province.cityList
            });
        }
    };
    ajax(opt1)
}

//赴台户籍滑动事件
function bindTWHouseChange(e, pageObj) {
    const current_page = e.detail.value, _data = pageObj.data;
    pageObj.setData({
        houseIndex: current_page
    })
}

//港澳签注初始化地址
function initHkHouse(pageObj) {
    pageObj.setData({
        isShow: false, // 显示区域选择框
        showDistrict: true // 默认为省市区三级区域选择
    });
    if (pageObj.data.visaType == 5) {//为深圳的时候，需要剔除广东省的
        var opt1 = {
            url: Host + "/wx/c/p.ajax",
            data: {},
            showLoadFlag: "false",
            sucFn: function (province) {
                var firstProvince = province.body.result[0];
                var provinceResult = [];

                //深圳类型
                for (var i = 0; i < province.body.result.length; i++) {
                    if (province.body.result[i].id != 440000) {
                        provinceResult.push(province.body.result[i])
                    }
                }
                pageObj.setData({//默认选择获取的省份第一个省份数据
                    hkHouseProviceData: provinceResult  //provinceResult //province.body.result// [provinceResult]
                });

                var opt2 = {
                    url: Host + "/wx/c/c1.ajax",
                    data: {"provinceId": firstProvince.id},
                    showLoadFlag: "false",
                    sucFn: function (city) {
                        var firstCity = city.body.result[0];
                        pageObj.setData({
                            hkHouseCityData: city.body.result
                        });
                        var opt3 = {
                            url: Host + "/wx/c/c2.ajax",
                            data: {"cityId": firstCity.id},
                            showLoadFlag: "false",
                            sucFn: function (district) {
                                pageObj.setData({
                                    hkHouseValue: [0, 0, 0],//默认广东省
                                    hkHouseDistrictData: district.body.result
                                });
                            }
                        };
                        ajax(opt3);
                    }
                };
                ajax(opt2);
            }
        };
        ajax(opt1)
    } else {
        var type = (pageObj.data.visaType == 2 ? 1 : pageObj.data.visaType);
        var opt1 = {
            url: Host + "/wx/ehk/qeca.ajax",
            data: {
                bizType: type,
                bizProvinceId: pageObj.data.bizProvinceId
            },
            showLoadFlag: "false",
            sucFn: function (result) {
                var province = result.body;

                pageObj.setData({//默认选择获取的省份第一个省份数据
                    hkHouseProviceData: [{
                        id: province.provinceId,
                        name: province.provinceName
                    }]
                });
                pageObj.setData({
                    hkHouseCityData: province.cityList
                });
                pageObj.setData({
                    hkHouseValue: [0, 0, 0],
                    hkHouseDistrictData: province.countyList
                });
            }
        };
        ajax(opt1)
    }
}

function bindHkHouseChange(e, pageObj) {
    const current_value = e.detail.value, _data = pageObj.data;
    if (current_value.length > 2) {
        if (pageObj.data.hkHouseValue[0] !== current_value[0]) {  // 滑动省份
            var opt1 = {
                url: Host + "/wx/c/c1.ajax",
                showLoadFlag: "false",
                data: {"provinceId": _data.hkHouseProviceData[current_value[0]].id},
                sucFn: function (city) {
                    pageObj.setData({
                        hkHouseValue: [current_value[0], 0, 0],
                        hkHouseCityData: city.body.result
                    });
                    var opt2 = {
                        url: Host + "/wx/c/c2.ajax",
                        showLoadFlag: "false",
                        data: {"cityId": city.body.result[0].id},
                        sucFn: function (district) {
                            if (district.body.result.length > 0) {
                                pageObj.setData({
                                    hkHouseDistrictData: district.body.result
                                });
                            }
                        }
                    };
                    ajax(opt2);
                }
            };
            ajax(opt1);
        } else if (pageObj.data.hkHouseValue[0] === current_value[0] && pageObj.data.hkHouseValue[1] !== current_value[1] && pageObj.data.hkHouseValue[2] === current_value[2]) { // 滑动城市
            if (pageObj.data.visaType == 5) {
                var opt = {
                    url: Host + "/wx/c/c2.ajax",
                    data: {"cityId": _data.hkHouseCityData[current_value[1]].id},
                    showLoadFlag: "false",
                    sucFn: function (district) {
                        if (district.body.result.length > 0) {
                            pageObj.setData({
                                hkHouseDistrictData: district.body.result,
                                hkHouseValue: [current_value[0], current_value[1], 0]
                            });
                        }
                    }
                };
                ajax(opt);
            } else {
                pageObj.setData({
                    hkHouseDistrictData: _data.hkHouseCityData[current_value[1]].result,
                    hkHouseValue: [current_value[0], current_value[1], 0]
                });
            }
        } else if (pageObj.data.hkHouseValue[0] === current_value[0] && pageObj.data.hkHouseValue[1] === current_value[1] && pageObj.data.hkHouseValue[2] !== current_value[2]) { // 滑动地区
            pageObj.setData({hkHouseValue: current_value});
        }
    }
}

function toast(msg, icon) {//只有成功和加载中提示
    var icon = (icon == null || icon == "" || typeof(icon) == "undefined") ? "success" : icon;
    wx.showToast({
        title: msg,
        icon: icon,
        duration: 2000
    });
}

function check(jsonArray, pageObj) {//自定义的校验接口
    var flag = true;
    for (var i = 0; i < jsonArray.length; i++) {
        var json = jsonArray[i];
        if (json.fn == null || json.fn == "" || typeof(json.fn) == "undefined") {
            if (json.rule.key == Rule.required.key
                && json.value == '') {
                errorToast(pageObj, json.message);
                pageObj.setData({
                    "errorFocusName": json.errorFocusName,
                    "errorScrollIntoViewName": json.errorScrollIntoViewName
                });
                flag = false;
                break;
            }
        } else {//自定义的验证函数
            if (!json.fn(json.value)) {
                pageObj.setData({
                    "errorFocusName": json.errorFocusName,
                    "errorScrollIntoViewName": json.errorScrollIntoViewName
                });
                flag = false;
                break;
            }
        }
    }
    return flag;
}

function errorToast(pageObj, mes) {//显示错误提醒
    // wx.showToast({
    //     title: mes,
    //     icon: 'none',
    //     duration: 2000
    // });
    showPopErrorMes(pageObj, mes);
    hidePopErrorMes(pageObj);
}

function hidePopErrorMes(pageObj) {
    var fadeOutTimeout = setTimeout(() => {
        pageObj.setData({popErrorMsg: ''});
        clearTimeout(fadeOutTimeout);
    }, 3000);
}

function showPopErrorMes(pageObj, mes) {
    pageObj.setData(
        {popErrorMsg: mes}
    );
}

function ajaxError(pageObj, mes) {
    try {
        errorToast(pageObj, mes);
    } catch (e) {
        console.log(mes);
    }
}

function ajax(opt) {
    opt.type = (opt.type == null || opt.type == "" || typeof(opt.type) == "undefined") ? "POST" : opt.type;
    opt.data = (opt.data == null || opt.data == "" || typeof(opt.data) == "undefined") ? {"date": new Date().getTime()} : opt.data;
    opt.sucFn = (opt.sucFn == null || opt.sucFn == "" || typeof(opt.sucFn) == "undefined") ? {"date": new Date().getTime()} : opt.sucFn;
    opt.showLoadFlag = (opt.showLoadFlag == null || opt.showLoadFlag == "" || typeof(opt.showLoadFlag) == "undefined") ? "true" : opt.showLoadFlag;

    if (opt.showLoadFlag == "true") {
        wx.showToast({
            title: '加载中',
            icon: 'loading',
            duration: 10000
        });
    }

    wx.request({
        url: opt.url,
        header: {'content-type': 'application/x-www-form-urlencoded'},
        data: opt.data,
        method: opt.type.toUpperCase(),
        success: function (res) {
            if (opt.showLoadFlag == "true") {
                wx.hideToast();
            }
            if (res.data.code == 4444) {//处理失败的结果
                if (res.data.msg.indexOf("accountId is blank.") > -1) {
                    opt.accountIdBlankFn();
                } else {
                    ajaxError(opt.pageObj, res.data.msg);                    
                }
            } else if (res.statusCode == 404) {
                ajaxError(opt.pageObj, '服务器出小差了，连接不上，请稍后重试！');
            } else {
                opt.sucFn(res.data);
            }
        },
        fail: function () {
            wx.hideLoading();
            if (opt.erFn == null || opt.erFn == "" || typeof(opt.erFn) == "undefined") {
                ajaxError(opt.pageObj, '请求出错');
            } else {
                opt.erFn();
            }
        },
        complete: function () {
            wx.hideLoading();
        }
    })
}

//时间戳转换时间
function toYMDDate(number) {
    var n = number;
    var date = new Date(n);
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    return Y + M + D;
}

//时间戳转换时间
function toYMDHMSDate(number) {
    var n = number;
    var date = new Date(n);
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    var h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    var minute = date.getMinutes();
    var second = date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;
    second = second < 10 ? ('0' + second) : second;
    return Y + M + D + ' ' + h + ':' + minute + ':' + second;
}

//微信支付
function requestPayment(opt) {
    wx.requestPayment({
        'timeStamp': opt.timeStamp,
        'nonceStr': opt.nonceStr,
        'package': opt.package,
        'signType': opt.signType,
        'paySign': opt.paySign,
        'success': function (res) {
            if (opt.sucFn != null && opt.sucFn != "" && typeof(opt.sucFn) != "undefined") {
                opt.sucFn(res);
            }
        },
        'fail': function (res) {
            if (opt.failFn != null && opt.failFn != "" && typeof(opt.failFn) != "undefined") {
                opt.failFn(res);
            }
        }
    })
}

module.exports = {
    Rule: Rule,
    Host: Host,
    FootConvenientService: FootConvenientService,
    toast: toast,
    errorToast: errorToast,
    hidePopErrorMes: hidePopErrorMes,
    check: check,
    initAddress: initAddress,
    bindAddressChange: bindAddressChange,
    bindTWHouseChange: bindTWHouseChange,
    initHkHouse: initHkHouse,
    initTwHouse: initTwHouse,
    bindHkHouseChange: bindHkHouseChange,
    ajax: ajax,
    toYMDDate: toYMDDate,
    toYMDHMSDate: toYMDHMSDate,
    requestPayment: requestPayment
};
